/**
 * <p>Package : org.tea.springdata.mongdb</p>
 * <p>E-Mail : ztlyde@gmail.com</p>
 */
package org.tea.springdata.mongdb;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.core.MongoFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;
import com.mongodb.MongoOptions;

/**
 * @author: John zhang
 * @version: 0.1
 */
@Configuration
@ComponentScan(basePackages = { "org.tea.springdata.mongdb" }, excludeFilters = { @Filter(Configuration.class) })
@Import( {AppXmlConfig.class} )
public class AppConfig {

	@Bean
	public MongoOperations mongoTemplate() {
		Mongo mongo = null;
		try {
			mongo = dbFactory().getObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		MongoTemplate mongoTemplate = new MongoTemplate(mongo, "blog");
		return mongoTemplate;
	}

	@Bean
	public MongoFactoryBean dbFactory() {
		MongoFactoryBean mongo = new MongoFactoryBean();
		mongo.setHost("192.168.2.65");
		mongo.setPort(27017);

		MongoOptions mOpt = new MongoOptions();
		mOpt.setConnectTimeout(1000);
		mOpt.setMaxWaitTime(1500);
		mOpt.setSocketKeepAlive(true);
		mOpt.setThreadsAllowedToBlockForConnectionMultiplier(5);
		mongo.setMongoOptions(mOpt);
		return mongo;
	}

	@Bean(name = { "mongoBlogDb" })
	public SimpleMongoDbFactory blogDB() {
		Mongo mongo = null;
		try {
			mongo = dbFactory().getObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 需要用户认证的, 在此加上认证标识
		UserCredentials uc = new UserCredentials("blog", "blog123");
		return new SimpleMongoDbFactory(mongo, "blog", uc);
	}

//	@Bean
//	public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
//		return new PersistenceExceptionTranslationPostProcessor();
//	}

}
